package com.cfpamf.ms.insur.pay.aspect;

import com.cfpamf.ms.insur.pay.facade.constant.PayConstant;
import com.cfpamf.ms.insur.pay.facade.util.SignUtil;
import com.cfpamf.ms.insur.pay.service.SignKeyService;
import com.cfpamf.ms.insur.pay.util.HttpRequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.lang.reflect.Type;
import java.util.Map;

/**
 * Create By zhengjing on 2019-10-21 17:36
 */
@Slf4j
@ControllerAdvice
public class RequestBodyValidSignAdvice extends RequestBodyAdviceAdapter {
    private static final String SIGN_TYPE_NAME = "com.cfpamf.common.ms.result.Result";

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private SignKeyService signKeyService;

    /**
     * 请求体
     * 只拦截返回值为{@link com.cfpamf.common.ms.result.Result}的方法
     * request supports
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        Class<?> returnType = methodParameter.getMethod().getReturnType();
        return StringUtils.startsWith(returnType.getCanonicalName(), SIGN_TYPE_NAME);
    }

    /**
     * 在body成功读取之后 校验签名
     */
    @Override
    @SuppressWarnings("unchecked")
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {

        if (body != null) {
            String sysKey = signKeyService.getKeyBySys(HttpRequestUtil.getHeader(PayConstant.HEADER_NAME_SYS));
            Map<String, Object> map = mapper.convertValue(body, Map.class);
            String signValue = HttpRequestUtil.getHeader(PayConstant.HEADER_NAME_SIGN);
            SignUtil.validSign(map, HttpRequestUtil.getHeader(PayConstant.HEADER_NAME_SIGN), sysKey);
            log.info("校验请求体的签名成功：{}==>{}", sysKey, signValue);
        }
        return body;
    }
}
